package com.itx.gatewayx.controller;

import com.itx.gatewayx.common.R;
import com.itx.gatewayx.domain.News;
import com.itx.gatewayx.domain.dto.NewsApiResponse;
import com.itx.gatewayx.service.NewsService;
import com.itx.gatewayx.task.NewsTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻API控制器
 *
 * @author itx
 */
@Slf4j
@RestController
@RequestMapping("/api/news-api")
@RequiredArgsConstructor
public class NewsApiController {

    private final NewsService newsService;
    private final NewsTask newsTask;
    
    /**
     * 手动获取新闻
     *
     * @param type 新闻类型
     * @param page 页码
     * @param pageSize 每页数量
     * @param isFilter 是否只返回有内容详情的新闻
     * @return 新闻数据
     */
    @GetMapping("/fetch")
    public R<NewsApiResponse> fetchNews(
            @RequestParam(required = false) String type,
            @RequestParam(required = false, defaultValue = "1") String page,
            @RequestParam(required = false, defaultValue = "20") String pageSize,
            @RequestParam(required = false, defaultValue = "1") String isFilter) {
        
        Map<String, String> params = new HashMap<>();
        params.put("type", type);
        params.put("page", page);
        params.put("page_size", pageSize);
        params.put("is_filter", isFilter);
        
        NewsApiResponse response = newsService.fetchNewsFromApi(params);
        if (response == null || (response.getErrorCode() != null && response.getErrorCode() != 0)) {
            return R.fail("获取新闻失败: " + (response == null ? "请求失败" : response.getReason()));
        }
        
        if (response.getErrorCode() == null && !"success".equalsIgnoreCase(response.getReason())) {
            return R.fail("获取新闻失败: " + response.getReason());
        }
        
        return R.ok(response);
    }
    
    /**
     * 手动触发单个随机类型的新闻数据抓取
     *
     * @return 结果
     */
    @GetMapping("/fetch-random")
    public R<String> fetchRandomNews() {
        new Thread(() -> {
            try {
                newsTask.manualFetchNews();
            } catch (Exception e) {
                log.error("手动执行随机新闻抓取任务失败", e);
            }
        }).start();
        
        return R.ok("随机新闻抓取任务已在后台启动");
    }
    
    /**
     * 手动触发所有新闻类型的数据抓取
     *
     * @return 结果
     */
    @GetMapping("/fetch-all")
    public R<String> fetchAllNews() {
        new Thread(() -> {
            try {
                newsTask.manualFetchAllNews();
            } catch (Exception e) {
                log.error("手动执行全量新闻抓取任务失败", e);
            }
        }).start();
        
        return R.ok("全量新闻抓取任务已在后台启动");
    }
    
    /**
     * 获取最新新闻列表
     *
     * @return 新闻列表
     */
    @GetMapping("/latest")
    public R<List<News>> getLatestNews() {
        List<News> newsList = newsService.getLatestNews();
        return R.ok(newsList);
    }
    
    /**
     * 按分类获取新闻列表
     *
     * @param category 分类
     * @return 新闻列表
     */
    @GetMapping("/category/{category}")
    public R<List<News>> getNewsByCategory(@PathVariable String category) {
        List<News> newsList = newsService.getNewsByCategory(category);
        return R.ok(newsList);
    }
} 